package com.coderly.onlinegallerysharingplatform.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.coderly.onlinegallerysharingplatform.common.response.Response;
import com.coderly.onlinegallerysharingplatform.common.oss.strategy.FileStrategy;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/file")
@Deprecated
public class FileController {

    @Resource
    private FileStrategy fileStrategy;

    /**
     * 文件上传接口
     *
     * @param multipartFile 上传的文件
     * @return 文件访问URL
     */
    @SaIgnore
    @PostMapping("/upload")
    public Response<?> uploadFile(@RequestParam("file") MultipartFile multipartFile){
        String filename = multipartFile.getOriginalFilename();
        String filepath = String.format("/test/%s", filename);
        File file = null;
        try {
            // 创建本地临时文件
            file = File.createTempFile(filepath, null);
            // 将前端传来的文件保存到本地临时文件中
            multipartFile.transferTo(file);
            fileStrategy.uploadFile(file, filepath);
            return Response.success(filepath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 删除本地临时文件
            boolean delete = file.delete();
            if (!delete) {
                log.error("删除本地临时文件失败");
            }
        }
    }

    @SaIgnore
    @GetMapping("/download")
    public void downloadFile(String filepath, HttpServletResponse response) {
        Object o = fileStrategy.downloadFile(filepath);
        if (o instanceof COSObject) {
            COSObject cosObject = (COSObject) o;
            COSObjectInputStream cosObjectInputStream = cosObject.getObjectContent();
            try {
                byte[] bytes = IOUtils.toByteArray(cosObjectInputStream);
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
                // 写入响应
                response.getOutputStream().write(bytes);
                response.getOutputStream().flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (cosObjectInputStream != null) {
                    try {
                        cosObjectInputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}

